package com.cssnj.portal.service.manage.apply;

import com.cssnj.portal.domain.manage.*;
import com.cssnj.portal.utils.PinYinUtils;
import com.cssnj.portal.utils.PortalUntil;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.constants.SysConstants;
import io.predictech.framework.domain.exception.BaseException;
import io.predictech.framework.service.base.BaseService;
import io.predictech.framework.utility.PredictechUtil;
import io.predictech.framework.utility.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * 应用申请服务
 *
 * @author Arthur
 * @version 1.0
 * @since 2018-9-11 20:15
 */
@Service
public class ApplyService extends BaseService {

    @Autowired
    private YyGnJrRepository jrRepository;

    @Autowired
    private YyGnJrXqSmRepository xqSmRepository;

    @Autowired
    private YyGnJrJsSmRepository jsSmRepository;

    @Override
    protected JsonResponse invokingService(JsonRequest jsonRequest) throws SQLException, BaseException {
        return null;
    }


    /**
     * @description 所属应用改变时返回应用信息
     * @author Arthur
     * @since 2018-9-17 9:56
     **/
    public JsonResponse ssYyChange(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();

        String ssYy = StringUtil.empty(jsonRequest.getReqData().get("ssYy"));

        if (StringUtils.isNotEmpty(ssYy)) {
            List<Map<String, Object>> jcXxList = PredictechUtil.getCodeData("YY_JCXX");
            Optional<Map<String, Object>> jcXxOptional = jcXxList.stream().filter(msg -> ssYy.equals(msg.get("YY_ID"))).findFirst();

            if (jcXxOptional.isPresent()) {
                jsonResponse.getRepData().put("href", jcXxOptional.get().get("YY_GW"));
            } else {
                PortalUntil.logger().error("当前应用不存在 -> yyId : " + ssYy);
                jsonResponse.setCode("E9036");
                jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
            }
        } else {
            PortalUntil.logger().error("应用ID不可为空 -> yyId : " + ssYy);
            jsonResponse.setCode("E9036");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
        }
        return jsonResponse;
    }

    /**
     * @description 获取应用信息
     * @author Arthur
     * @since 2018/9/11 21:47
     **/
    public JsonResponse getAppMsg() {
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.getRepData().put("yyJcXx", PredictechUtil.getCodeData("YY_JCXX"));
        return jsonResponse;
    }

    /**
     * @description 创建应用申请
     * @author Arthur
     * @since 2018/9/11 23:29
     **/
    @SuppressWarnings({"ImplicitArrayToString", "unchecked"})
    public JsonResponse establishApply(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();

        PortalUntil.logger().debug("开始创建功能申请");

        // 检查上级功能ID是否存在
        if (StringUtils.isEmpty(StringUtil.empty(jsonRequest.getReqData().get("sjGn")))) {
            PortalUntil.logger().error("上级功能ID不可为空");
            jsonResponse.setCode("E9036");
            jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
            return jsonResponse;
        }

        // 检查功能链接是否startWith应用官网
        jsonResponse = ssYyChange(jsonRequest);
        String href;
        if (!SysConstants.SUCESS_CODE.equals(jsonResponse.getCode())) {
            return jsonResponse;
        } else {
            href = jsonRequest.getReqData().get("funcHref").toString();
            String gwHref = jsonResponse.getRepData().get("href").toString();
            if (!href.startsWith(gwHref)) {
                PortalUntil.logger().error("功能链接与应用链接应在同一域内 -> yyHref : " + gwHref + " funcHref : " + href);
                jsonResponse.setCode("W1097");
                jsonResponse.setMsg(this.getXxnr(jsonResponse.getCode()));
                return jsonResponse;
            }
        }

        String funcId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        String gnMc = jsonRequest.getReqData().get("gnMc").toString();

        PortalUntil.logger().info("合规校验结束开始创建申请 -> gnMc : " + gnMc);

        String sjGn = jsonRequest.getReqData().get("sjGn").toString();
        String ssYy = jsonRequest.getReqData().get("ssYy").toString();
        String funcExplain = jsonRequest.getReqData().get("funcExplain").toString();
        String demandExplain = StringUtil.castBase64ToStr(jsonRequest.getReqData().get("demandExplain").toString());
        String technologyExplain = StringUtil.castBase64ToStr(jsonRequest.getReqData().get("technologyExplain").toString());

        YyGnJrEntity jrEntity = new YyGnJrEntity();
        jrEntity.setGnMc(gnMc);
        jrEntity.setGnId(funcId);
        jrEntity.setGnms(funcExplain);
        jrEntity.setGnJc(PinYinUtils.getPinYinHeadChar(gnMc));
        jrEntity.setJssm(technologyExplain);
        jrEntity.setXqsm(demandExplain);
        jrEntity.setSjgnId(sjGn);
        jrEntity.setYyid(ssYy);
        jrEntity.setHref(href);
        jrEntity.setStatus("01");
        jrEntity.setBeKjfs("1");
        jrEntity.setXybj("1");
        jrEntity.setKzBj("1");
        jrEntity.setXsBj("1");
        jrEntity.setLrsj(this.queryDao.getSystimestamp());

        jrRepository.save(jrEntity);

        PortalUntil.logger().debug("申请创建结束 -> gnMc : " + gnMc);

        // 将功能ID传出
        jsonRequest.getReqData().put("funcId", funcId);

        return jsonResponse;
    }

    /**
     * @description 保存应用附件路径
     * @author Arthur
     * @since 2018-9-17 14:31
     **/
    @SuppressWarnings("unchecked")
    public JsonResponse saveAttachPath(JsonRequest jsonRequest) throws SQLException {
        JsonResponse jsonResponse = new JsonResponse();

        String funcId = jsonRequest.getReqData().get("funcId").toString().toLowerCase();
        Timestamp nowTime = this.queryDao.getSystimestamp();

        PortalUntil.logger().debug("开始保存功能附件 -> funcId : " + funcId);

        if (null != jsonRequest.getReqData().get("attachList")) {
            List<Map<String, String>> attachList = (List<Map<String, String>>) jsonRequest.getReqData().get("attachList");

            PortalUntil.logger().debug("功能附件 -> attachListSize : " + attachList.size());

            attachList.forEach(attach -> {
                if (attach.get("fileDm").startsWith("demandExplainFile")) {
                    // 需求
                    YyGnJrXqSmEntity xqSmEntity = new YyGnJrXqSmEntity();
                    xqSmEntity.setGnId(funcId);
                    try {
                        xqSmEntity.setFjmc(new String(attach.get("fileMc").getBytes(StringUtil.getCharset(attach.get("fileMc"))), StandardCharsets.UTF_8));
                    } catch (UnsupportedEncodingException e) {
                        xqSmEntity.setFjmc(attach.get("fileMc"));
                    }
                    xqSmEntity.setFjlj(attach.get("fileScDz"));
                    xqSmEntity.setLrSj(nowTime);
                    xqSmRepository.save(xqSmEntity);
                } else if (attach.get("fileDm").startsWith("technologyExplainFile")) {
                    YyGnJrJsSmEntity jsSmEntity = new YyGnJrJsSmEntity();
                    jsSmEntity.setGnId(funcId);
                    try {
                        jsSmEntity.setFjmc(new String(attach.get("fileMc").getBytes(StringUtil.getCharset(attach.get("fileMc"))), StandardCharsets.UTF_8));
                    } catch (UnsupportedEncodingException e) {
                        jsSmEntity.setFjmc(attach.get("fileMc"));
                    }
                    jsSmEntity.setFjlj(attach.get("fileScDz"));
                    jsSmEntity.setLrSj(nowTime);
                    jsSmRepository.save(jsSmEntity);
                }
            });
        }

        PortalUntil.logger().debug("功能附件保存结束 -> funcId : " + funcId);

        return jsonResponse;
    }
}
